package network;

import java.io.DataInputStream;
import java.io.IOException;

import datatypes.MCString;

import exceptions.MCConnectionException;

public class ConnectionReader {
	
	
	private DataInputStream di;
	
	public ConnectionReader(DataInputStream di) {
		this.di = di;
	}
	
	
	public synchronized int read() throws MCConnectionException {
		try {
			return di.read();
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	public synchronized boolean readBoolean() throws MCConnectionException {
		try {
			return di.read() == 1;
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	
	
	
	public synchronized short readShort() throws MCConnectionException {
		try {
			return di.readShort();
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	
	
	
	
	public synchronized int readInt() throws MCConnectionException {
		try {
			return di.readInt();
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	public synchronized float readFloat() throws MCConnectionException {
		try {
			return di.readFloat();
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	
	
	
	public synchronized double readDouble() throws MCConnectionException {
		try {
			return di.readDouble();
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	public synchronized Long readLong() throws MCConnectionException {
		try {
			return di.readLong();
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	
	
	
	public synchronized byte[] readBytes(int numberofbytes) throws MCConnectionException {
		byte[] bytes = new byte[numberofbytes];
		try {
			di.read(bytes);
			return bytes;
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
	
	public synchronized String readString() throws MCConnectionException {
		//length * 2: UTF16 uses 2 bytes, the client just sends the number of tokens.
		int namelength = readShort() * 2;
		return MCString.fromBytes(readBytes(namelength));
	}
	

	
	
	/**
	 * Skip some bytes from the inputbuffer.
	 * Bytes can be skipped if they are unused by the server.
	 * It should be a bit faster then putting the values into
	 * memory.
	 * @param i The number of bytes to skip.
	 * @throws MCConnectionException
	 */
	public void skipBytes(int i) throws MCConnectionException {
		try {
			di.skipBytes(8);
		} catch (IOException e) {
			throw new MCConnectionException();
		}
	}
}
